import { createAnnularSector } from './common'
import { highlightEntityManager } from './entities'
export class PolarGridHighlighter {
  constructor(viewer, center, angleStep, radiusStep) {
    this.viewer = viewer
    this.center = center
    this.angleStep = angleStep
    this.radiusStep = radiusStep
    this.entities = []
  }

  updateFromWebSocket(data) {
    this.clear()
    data.forEach(params => {
      const entity = this.createHighlightEntity(params)
      this.entities.push(entity)
    })
  }

  createHighlightEntity(params) {
    const geoRange = this.convertToGeoRange(params)
    const positions = this.calculateSectorPositions(geoRange)

    return this.viewer.entities.add({
      polygon: {
        hierarchy: new Cesium.PolygonHierarchy(positions),
        material: Cesium.Color.RED.withAlpha(0.3),
        outline: true,
        outlineColor: Cesium.Color.RED
      }
    })
  }

  convertToGeoRange(params) {
    // 假设单元格索引从1开始
    const minRadius = (params.distanceCellStart - 1) * this.radiusStep;
    const maxRadius = params.distanceCellEnd * this.radiusStep;

    // 修正角度起始偏移
    const startAngle = Cesium.Math.toRadians(
      (params.directionCellStart - 1) * this.angleStep
    );
    const endAngle = Cesium.Math.toRadians(
      params.directionCellEnd * this.angleStep
    );

    return { minRadius, maxRadius, startAngle, endAngle };
  }

  calculateSectorPositions(range) {
    const positions = []
    const angleSteps = 20

    // 生成内圈坐标
    for (let i = 0; i <= angleSteps; i++) {
      const angle = Cesium.Math.lerp(
        range.startAngle,
        range.endAngle,
        i / angleSteps
      )
      positions.push(this.calculateCartesian(range.minRadius, angle))
    }

    // 生成外圈坐标（反向）
    for (let i = angleSteps; i >= 0; i--) {
      const angle = Cesium.Math.lerp(
        range.startAngle,
        range.endAngle,
        i / angleSteps
      )
      positions.push(this.calculateCartesian(range.maxRadius, angle))
    }

    return positions
  }

  calculateCartesian(radius, angle) {
    const offset = new Cesium.Cartesian3(
      radius * Math.cos(angle),
      radius * Math.sin(angle),
      0
    )
    return Cesium.Matrix4.multiplyByPoint(
      Cesium.Transforms.eastNorthUpToFixedFrame(this.center),
      offset,
      new Cesium.Cartesian3()
    )
  }

  clear() {
    this.entities.forEach(e => this.viewer.entities.remove(e))
    this.entities = []
  }
}
export function createHighlightRegions(viewer, centerLonLat, params, angleMin, radiusMin, angelInterval, radiusInterval, colorType, id) {
  // 先清除旧数据
  highlightEntityManager.clearById(viewer);
  const newEntities = [];

  params.forEach((param, index) => {
    // 校验并处理参数
    const innerRadius = (radiusMin + param.distanceCellStart * angelInterval) * 1000;
    const outerRadius = (radiusMin + param.distanceCellEnd * angelInterval) * 1000;
    let startAngle = angleMin + param.directionCellStart * radiusInterval;
    let endAngle = angleMin + param.directionCellEnd * radiusInterval;

    if (innerRadius >= outerRadius) {
      console.error('Invalid radius range');
      return;
    }

    // 确保角度有效
    if (startAngle > endAngle) {
      [startAngle, endAngle] = [endAngle, startAngle];
    }

    // 生成顶点
    const positions = createAnnularSector(centerLonLat, innerRadius, outerRadius, startAngle, endAngle);
    // 添加高亮区域到地图
    const entity = viewer.entities.add({
      id: `${id}_${index}`, // 组合唯一ID
      polygon: {
        hierarchy: new Cesium.PolygonHierarchy(positions),
        material: colorType ? Cesium.Color.fromCssColorString(colorType).withAlpha(0.6) : Cesium.Color.BLUE.withAlpha(0.6),
        outline: true,
        outlineColor: Cesium.Color.TRANSPARENT,
        height: 0, // 贴地渲染
        extrudedHeight: undefined,
        classificationType: Cesium.ClassificationType.TERRAIN // 控制叠加关系
      }
    });
    newEntities.push(entity)
  });
  // 存储新实体组
  highlightEntityManager.addEntities(id, newEntities);
}
